using AutoMapper;
using Microsoft.Extensions.Logging;
using Sheep_Breeding.Domain.production_b;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Write.Api.DTOs;
using Sheep_Breeding.Write.Api.OperationServices.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sheep_Breeding.Write.Api.OperationServices.Services
{
    /// <summary>
    /// 羊只死亡记录服务实现类
    /// </summary>
    public class SheepDeathServices : ISheepDeathServices
    {
        private readonly ILogger<SheepDeathServices> logger;
        private readonly IMapper mapper;
        private readonly IBaseRepository<SheepDeath> sheepDeathRepository;
        private readonly EFDbContext db;

        public SheepDeathServices(
            ILogger<SheepDeathServices> logger,
            IMapper mapper,
            IBaseRepository<SheepDeath> sheepDeathRepository,
            EFDbContext db)
        {
            this.logger = logger;
            this.mapper = mapper;
            this.sheepDeathRepository = sheepDeathRepository;
            this.db = db;
        }

        /// <summary>
        /// 添加羊只死亡记录
        /// </summary>
        /// <param name="dto">添加羊只死亡记录的DTO</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> AddSheepDeath(AddSheepDeathDto dto)
        {
            logger.LogInformation("添加羊只死亡记录操作");
            var res = new ApiResult();
            try
            {
                if (dto == null)
                {
                    res.msg = "请求数据不能为空";
                    logger.LogWarning("请求数据为空");
                    return res;
                }
                var model = mapper.Map<SheepDeath>(dto);
                if (model == null)
                {
                    res.msg = "数据映射失败";
                    logger.LogError("AutoMapper映射失败");
                    return res;
                }
                model.CreateTime = DateTime.Now;
                // 保证这些字段不为null
                model.ModifierId = model.ModifierId ?? string.Empty;
                model.ModifyTime = model.ModifyTime ?? DateTime.Now;
                model.AuditorId = model.AuditorId ?? string.Empty;
                model.AuditTime = model.AuditTime ?? DateTime.Now;
                var info = await sheepDeathRepository.AddAsyn(model);
                logger.LogInformation($"数据库操作完成，影响行数: {info}");
                if (info > 0)
                {
                    res.success("羊只死亡记录添加成功");
                    logger.LogInformation($"羊只死亡记录添加成功，ID: {model.Id}");
                }
                else
                {
                    res.msg = "羊只死亡记录添加失败";
                    logger.LogWarning("羊只死亡记录添加失败");
                }
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只死亡记录添加异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"添加羊只死亡记录失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 删除羊只死亡记录（逻辑删除）
        /// </summary>
        /// <param name="id">羊只死亡记录主键id</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> DeleteSheepDeath(long id)
        {
            logger.LogInformation($"羊只死亡记录删除操作，ID: {id}");
            var res = new ApiResult();
            try
            {
                var info = await sheepDeathRepository.GetValue(x => x.Id == id);
                if (info != null)
                {
                    // 逻辑删除：假设有 IsDeleted 字段
                    info.Remark = "已删除"; // 或 info.IsDeleted = true;
                    var model = await sheepDeathRepository.Update(info);
                    if (model > 0)
                    {
                        res.success("删除成功");
                        logger.LogInformation($"羊只死亡记录删除成功，ID: {id}");
                    }
                    else
                    {
                        res.msg = "删除失败";
                        logger.LogWarning($"羊只死亡记录删除失败，ID: {id}");
                    }
                }
                else
                {
                    res.msg = "记录不存在";
                    logger.LogWarning($"羊只死亡记录不存在，ID: {id}");
                }
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只死亡记录删除异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"删除羊只死亡记录失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 修改羊只死亡记录
        /// </summary>
        /// <param name="dto">修改羊只死亡记录的DTO</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> UpdateSheepDeath(UpdateSheepDeathDto dto)
        {
            logger.LogInformation($"羊只死亡记录更新操作，ID: {dto.Id}");
            var res = new ApiResult();
            try
            {
                var existingRecord = await sheepDeathRepository.GetValue(x => x.Id == dto.Id);
                if (existingRecord != null)
                {
                    mapper.Map(dto, existingRecord);
                    existingRecord.ModifyTime = DateTime.Now;
                    // 保证这些字段不为null
                    existingRecord.ModifierId = existingRecord.ModifierId ?? string.Empty;
                    existingRecord.AuditorId = existingRecord.AuditorId ?? string.Empty;
                    existingRecord.AuditTime = existingRecord.AuditTime ?? DateTime.Now;
                    var model = await sheepDeathRepository.Update(existingRecord);
                    if (model > 0)
                    {
                        res.success("羊只死亡记录更新成功");
                        logger.LogInformation($"羊只死亡记录更新成功，ID: {dto.Id}");
                    }
                    else
                    {
                        res.msg = "羊只死亡记录更新失败";
                        logger.LogWarning($"羊只死亡记录更新失败，ID: {dto.Id}");
                    }
                }
                else
                {
                    res.msg = "记录不存在";
                    logger.LogWarning($"羊只死亡记录不存在，ID: {dto.Id}");
                }
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"羊只死亡记录更新异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"更新羊只死亡记录失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 查询所有羊只死亡记录（含栋舍名称，遍历赋值）
        /// </summary>
        public async Task<ApiResult<List<SheepDeathWithHouseDto>>> GetAllSheepDeaths()
        {
            logger.LogInformation("查询所有羊只死亡记录操作");
            var res = new ApiResult<List<SheepDeathWithHouseDto>>();
            try
            {
                var list = sheepDeathRepository.Getlist().ToList();
                var dtos = mapper.Map<List<SheepDeathWithHouseDto>>(list);

                // 关联栋舍名称
                foreach (var item in dtos)
                {
                    if (item.Buildings != null)
                    {
                        var house = await db.housetypeinfos.FindAsync(item.Buildings);
                        item.HousetypeName = house?.DongsheName;
                    }
                }

                res.success("查询所有羊只死亡记录成功", dtos);
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"查询所有羊只死亡记录异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"查询所有羊只死亡记录失败: {ex.Message}";
                return res;
            }
        }

        /// <summary>
        /// 按条件查询羊只死亡记录
        /// </summary>
        /// <param name="earNumber">羊只耳号</param>
        /// <param name="deathDate">死亡日期</param>
        /// <returns>查询结果</returns>
        public async Task<ApiResult<List<SheepDeathDto>>> SearchSheepDeaths(string earNumber, DateTime? deathDate)
        {
            logger.LogInformation("按条件查询羊只死亡记录操作");
            var res = new ApiResult<List<SheepDeathDto>>();
            try
            {
                var query = sheepDeathRepository.Getlist().AsQueryable();
                if (!string.IsNullOrEmpty(earNumber))
                    query = query.Where(x => x.SheepEarNumber.Contains(earNumber));
                if (deathDate.HasValue)
                    query = query.Where(x => x.DeathDate.Date == deathDate.Value.Date);
                var dtos = mapper.Map<List<SheepDeathDto>>(query.ToList());
                res.success("按条件查询羊只死亡记录成功", dtos);
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError($"按条件查询羊只死亡记录异常: {ex.Message}");
                logger.LogError($"异常堆栈: {ex.StackTrace}");
                res.msg = $"按条件查询羊只死亡记录失败: {ex.Message}";
                return res;
            }
        }
    }
} 